<template>
  <div class="authorize"></div>
</template>
<script>
  import {mapMutations} from 'vuex'

  export default {
    name: 'Authorize',
    computed: {},
    created() {
      this.directRightUrl()
    },
    mounted() {
      this.getToken();
      // this.authorize();
    },

    data() {
      return {
        token: ''
      }
    },

    methods: {
      ...mapMutations(['changeUser']),
      directRightUrl() {
        let {href, protocol, host, search, hash} = window.location
        const pathname = '/psy/wechat/' // 解决支付路径问题添加的前缀，
        search = search || '?'
        hash = hash || '#/'
        let newHref = `${protocol}//${host}${pathname}${search}${hash}`
        if (newHref !== href) {
          window.location.replace(newHref)
        }
      },
      authorize() {
        if (!this.$cookies.get('token')) {
          let ua = window.navigator.userAgent.toLowerCase()
          if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            // 跳转到微信授权页面
            window.location.href = 'http://test.psyelephant.com/index/api/userLogin'

          } else {
            // this.login()
            alert("请在微信浏览器打开")
          }
        } else {
          // alert('login')
          this.login()

        }
      },

      getToken() {
        let tk = this.$route.query.token
        this.token = tk
        if (this.token) {
          this.$cookies.set("token", '');
          this.$cookies.set('token', this.token, 60 * 60)
          this.login()
        } else {
          console.log('token is null')
          this.authorize()
        }
      },

      login() {
        let token = this.$cookies.get('token')
        this.axios({
          method: 'post',
          url: '',
          data: {
            token
          }
        }).then((res) => {
          if (res) {
            this.changeUser(res.data)
            this.goBeforeLoginUrl()
          } else {
            this.$cookies.remove('token')
            this.authorize()
          }
        })
      }
    }
  }
</script>
<style scoped>
  .authorize {
    position: absolute;
    z-index: 30;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
</style>
